package com.nuc.thread.unsafe;

import lombok.ToString;
import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.time.format.DateTimeFormatter;

/**
 * @author 诗酒趁年华
 * @version 1.0.0
 * @Description 获得unsafe对象
 * @createTime 2021年07月31日 23:40:00
 */
public class Test1 {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);

        Unsafe unsafe = (Unsafe) theUnsafe.get(null);
        //System.out.println(unsafe);

        //获得偏移量
        long idOffset = unsafe.objectFieldOffset(Student.class.getDeclaredField("id"));
        long nameOffset = unsafe.objectFieldOffset(Student.class.getDeclaredField("name"));

        Student student = new Student();
        //执行cas操作
        unsafe.compareAndSwapInt(student,idOffset,0,11);
        unsafe.compareAndSwapObject(student,nameOffset,null,"lisi");

        System.out.println(student);


    }
}
@ToString
class Student{
    volatile int id;
    volatile String name;
}
